package universe;

import universe.utils.Vector3D;

public class movingBehaviour {

	private CelestialBody owner;
	private Vector3D objAcel;

	public movingBehaviour(CelestialBody owner) {
		this.owner = owner;
		objAcel = new Vector3D();
	}

	// Algoritmo de velocidad-Vernet
	// http://phet.colorado.edu/sims/my-solar-system/my-solar-system_es.html
	public void updateStats(Vector3D fRes, float timeInterval) {
		Vector3D newPos = new Vector3D();
		Vector3D newVel = new Vector3D();
		newVel = calcNewVel(fRes, timeInterval);
		newPos = calcNewPos(fRes, timeInterval);

		//Vector3D aux = new Vector3D(fRes);
		//aux.div(owner.getMass(), objAcel);
		fRes.div(owner.getMass(), objAcel);

		owner.setPosition(newPos);
		owner.setVelocity(newVel);
	}

	// ------ X_n+1 = X_n + V_n * t + a_n * t^2 * 0.5 ---
	private Vector3D calcNewPos(Vector3D fRes, double dt) {
		Vector3D ans = owner.getPosition().clone(); // X_n
		Vector3D aux = objAcel.clone();

		aux.mult((float) (dt * dt * 0.5));
		ans.add(aux); // + a_n * t^2 / 2
		aux = owner.getVelocity().clone();
		aux.mult((float) dt);
		ans.add(aux);// + V_n * t

		return ans;
	}

	// ------ V_n+1 = (a_n+1 + a_n) * t * 0.5 + V_n -----
	private Vector3D calcNewVel(Vector3D fRes, double dt) {
		Vector3D ans = owner.getVelocity().clone(); // V_n

		Vector3D an = objAcel.clone();
		Vector3D an1 = fRes.clone();
		an1.div(owner.getMass());
		an.add(an1);
		an.mult((float) (dt * 0.5));

		ans.add(an); // + (a_n+1 + a_n) * t * 0.5
		return ans;
	}

}
